package com.hyy.provider.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hyy.api.domain.customer.vo.CstmCustomerVo;
import com.hyy.api.domain.provider.ProvProvider;
import com.hyy.api.domain.provider.bo.ProvProviderBo;
import com.hyy.api.domain.provider.bo.ProvProviderParamBo;
import com.hyy.api.domain.provider.vo.ProvApiProgramTemplateVo;
import com.hyy.api.domain.provider.vo.ProvProviderParamVo;
import com.hyy.api.domain.provider.vo.ProvProviderVo;
import com.hyy.common.core.utils.MapstructUtils;
import com.hyy.common.core.utils.StringUtils;
import com.hyy.common.mybatis.core.page.PageQuery;
import com.hyy.common.mybatis.core.page.TableDataInfo;
import com.hyy.common.redis.utils.RedisUtils;
import com.hyy.provider.mapper.ProvProviderMapper;
import com.hyy.provider.service.IProvApiProgramTemplateService;
import com.hyy.provider.service.IProvProviderParamService;
import com.hyy.provider.service.IProvProviderService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import static com.hyy.api.constant.BusinessRedisConstants.CSTM_CUSTOMER_START;
import static com.hyy.api.constant.BusinessRedisConstants.CSTM_PROVIDER_START;

/**
 * 上游供应商Service业务层处理
 *
 * @author ruoyi
 * @date 2025-05-19
 */
@RequiredArgsConstructor
@Service
public class ProvProviderServiceImpl implements IProvProviderService {

    private final ProvProviderMapper baseMapper;
    private final IProvProviderParamService provProviderParamService;
    private final IProvApiProgramTemplateService provApiProgramTemplateService;

    /**
     * 查询上游供应商
     *
     * @param id 主键
     * @return 上游供应商
     */
    @Override
    public ProvProviderVo queryById(Long id){
        ProvProviderVo provProviderVo = baseMapper.selectVoById(id);
        Long apiProgramId = provProviderVo.getApiProgramId();
        //获取参数模板
        List<ProvApiProgramTemplateVo> provApiProgramTemplateVos = provApiProgramTemplateService.queryListByApiProgramId(apiProgramId);
        //获取参数列表
        List<ProvProviderParamVo> provProviderParamVos = provProviderParamService.queryListByProviderId(id);

        //遍历参数模板，将参数列表中的值赋值给参数模板
        for (ProvApiProgramTemplateVo provApiProgramTemplateVo : provApiProgramTemplateVos) {
            String fieldName1 = provApiProgramTemplateVo.getFieldName();
            for (ProvProviderParamVo provProviderParamVo : provProviderParamVos) {
                String fieldName2 = provProviderParamVo.getFieldName();
                if (fieldName1.equals(fieldName2)){
                    provApiProgramTemplateVo.setValue(provProviderParamVo.getFieldValue());
                }
            }
        }
        provProviderVo.setTemplateParams(provApiProgramTemplateVos);

        return provProviderVo;
    }

    /**
     * 分页查询上游供应商列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 上游供应商分页列表
     */
    @Override
    public TableDataInfo<ProvProviderVo> queryPageList(ProvProviderBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ProvProvider> lqw = buildQueryWrapper(bo);
        Page<ProvProviderVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的上游供应商列表
     *
     * @param bo 查询条件
     * @return 上游供应商列表
     */
    @Override
    public List<ProvProviderVo> queryList(ProvProviderBo bo) {
        LambdaQueryWrapper<ProvProvider> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ProvProvider> buildQueryWrapper(ProvProviderBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ProvProvider> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(ProvProvider::getId);
        lqw.like(StringUtils.isNotBlank(bo.getName()), ProvProvider::getName, bo.getName());
        lqw.eq(StringUtils.isNotBlank(bo.getCode()), ProvProvider::getCode, bo.getCode());
        lqw.eq(bo.getStatus() != null, ProvProvider::getStatus, bo.getStatus());
        lqw.eq(bo.getApiProgramId() != null, ProvProvider::getApiProgramId, bo.getApiProgramId());
        lqw.eq(bo.getCorporateId() != null, ProvProvider::getCorporateId, bo.getCorporateId());
        return lqw;
    }

    /**
     * 新增上游供应商
     *
     * @param bo 上游供应商
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(ProvProviderBo bo) {
        List<ProvProviderParamBo> paramsList = bo.getParamsList();
        ProvProvider add = MapstructUtils.convert(bo, ProvProvider.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            if(CollUtil.isNotEmpty(paramsList)){
                provProviderParamService.saveBatch(add.getId(),paramsList);
            }
        }
        return flag;
    }

    /**
     * 修改上游供应商
     *
     * @param bo 上游供应商
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(ProvProviderBo bo) {
        List<ProvProviderParamBo> paramsList = bo.getParamsList();
        ProvProvider update = MapstructUtils.convert(bo, ProvProvider.class);
        validEntityBeforeSave(update);
        boolean flag = baseMapper.updateById(update) > 0;
        if (flag){
            if(CollUtil.isNotEmpty(paramsList)){
                provProviderParamService.saveBatch(bo.getId(),paramsList);
            }
        }

        return flag;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ProvProvider entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除上游供应商信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    public ProvProviderVo newProvider() {
        Integer cstm_provider_start = RedisUtils.getCacheObject(CSTM_PROVIDER_START);
        if(cstm_provider_start == null){
            RedisUtils.setCacheObject(CSTM_PROVIDER_START, 300000);
        }


        long code = RedisUtils.incrAtomicValue(CSTM_PROVIDER_START);
        ProvProviderVo provProviderVo = new ProvProviderVo();
        provProviderVo.setCode(code+"");
        provProviderVo.setStatus(1);

        return provProviderVo;
    }
}
